package com.ht.api.call.func.impl.ad;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import javax.sql.DataSource;

import com.ht.api.bean.AjaxResult;
import com.ht.api.bean.LoginBean;
import com.ht.api.business.ad.PlanHelper;
import com.ht.api.call.ICall;
import com.ht.api.call.func.IFunctionCall;
import com.ht.api.db.Db;
import com.ht.api.db.DbConfig;
import com.ht.api.db.Entity;
import com.ht.api.db.StreamLoadConfig;
import com.ht.api.util.UserUtil;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 新增旅程的后置函数
 * @author asq
 * @createTime 2025年3月1日 14:01:20
 */
@Slf4j
public class StageAddFunctionCall implements IFunctionCall {

	@Override
	public String getName() {
		return "新增旅程后置函数";
	}

	@Override
	public JSONObject execute(LoginBean me, JSONObject param, AjaxResult result) {
		log.info("触发新增旅程后置函数...");
		createStagePlan(me, param, result);

		return JSONUtil.createObj();
	}

	/**
	 * 创建旅程相关的营销策略，策略广告，广告计划
	 * @param me 
	 * @param result
	 */
	private void createStagePlan(LoginBean me, JSONObject param, AjaxResult result) {
		DataSource ds = me.getDataSource();

		// 构造param
		JSONObject paramObj = JSONUtil.createObj();
		paramObj.set("name", "阶段：" + param.getStr("name"));
		paramObj.set("source_id", result.get(ICall.MAIN_ID));
		paramObj.set("source_type", "sop");
		paramObj.set("user_refresh_type", 1);
		paramObj.set("cycle_type", "PERMANENT");
		paramObj.set("exec_type", 1);

		String sopId = param.getStr("sop_id");
		Entity sop = Db.createSqlParser("sop").where("main_id", sopId).findOne(ds);
		paramObj.set("priority", sop.get("priority"));
		paramObj.set("audience_rule", sop.get("audience_rule"));
		paramObj.set("app_rule", sop.get("app_rule"));
		paramObj.set("condition", param.get("condition"));

		// 创建营销策略，策略广告，广告计划
		createPlanByStage(paramObj);

		Entity entity = Entity.create("stage");
		entity.set("main_id", result.get(ICall.MAIN_ID));
		entity.set("plan_id", paramObj.get("plan_id"));
		entity.set("campaign_id", paramObj.get("campaign_id"));
		entity.set("status", -1);

		Db.insert(ds, entity);
	}

	/**
	 * 根据旅程创建营销策略，策略广告，广告计划
	 * @param param 旅程
	 */
	private void createPlanByStage(JSONObject param) {
		long tenantId = UserUtil.getLoginUser().getTenantId();
		StreamLoadConfig config = DbConfig.useTenantSLC(tenantId);

		List<Entity> dataList = new CopyOnWriteArrayList<>();

		// 创建营销策略，策略广告，广告计划
		Entity adCampaign = PlanHelper.generateCampaign(param);
		dataList.add(adCampaign);
		Entity adPlan = PlanHelper.generatePlan(param);
		dataList.add(adPlan);

		// 保存
		Db.insertBatchWithStream(config, dataList);
	}

}
